package com.github.thinwonton.activemq.showcase.prefetch;

import com.github.thinwonton.activemq.showcase.ActiveMQManager;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQPrefetchPolicy;

import javax.jms.*;
import java.io.IOException;

public class HighPrefetchSizeConsumer {
    public static void main(String[] args) throws IOException {
        try {
            ActiveMQConnection activeMQConnection = (ActiveMQConnection)ActiveMQManager.createConnection();
            ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy();
            prefetchPolicy.setQueuePrefetch(10);
            activeMQConnection.setPrefetchPolicy(prefetchPolicy); //预取策略
            activeMQConnection.setOptimizeAcknowledge(true); //可优化的ACK，延迟确认
            activeMQConnection.setOptimizeAcknowledgeTimeOut(100000);
            activeMQConnection.start();

            Session session = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(Utils.QUEUE_NAME);
            MessageConsumer consumer = session.createConsumer(queue);

            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        System.out.println("-------- ----- --------- ");
                        System.out.println("触发消息接收");
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        handleMsg(text);
                        System.out.println("成功处理消息 : " + text);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                }
            });

            System.out.println("is OptimizeAck:" + activeMQConnection.isOptimizeAcknowledge());
            System.out.println("OptimizeAck timeout:" + activeMQConnection.getOptimizeAcknowledgeTimeOut());


            // 线程一直等待
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void handleMsg(String msg) {
        System.out.println("准备处理消息 : " + msg);
        try {
            Thread.sleep(5000);  //5秒处理一个
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
